package com.neo.redis.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
// import java.lang.Thread;

import javax.servlet.http.HttpSession;

import com.neo.common.BaseResult;
import com.neo.redis.model.User;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@RestController
@RequestMapping(path = "/api/redis")
public class RedisAPIController {

    @Value("${spring.redis.database}")
    private String db;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/info")
    public BaseResult getDBInfo() {
        Map<String, String> info = new HashMap<String, String>();
        info.put("db", db);
        info.put("host", host);
        info.put("port", port);
        return BaseResult.successWithData(info);
    }

    // @GetMapping("/test1")
    // public void test1() {
    // stringRedisTemplate.opsForValue().set("aaa", "111");
    // }

    // @GetMapping("/test2")
    // public void test2() {
    // User user = new User("aa@126.com", "aa", "aa123456", "aa", "123");
    // ValueOperations<String, User> operations = redisTemplate.opsForValue();
    // operations.set("com.neox", user);
    // operations.set("com.neo.f", user, 1, TimeUnit.SECONDS);
    // // Thread.sleep(1000);
    // // redisTemplate.delete("com.neo.f");
    // boolean exists = redisTemplate.hasKey("com.neo.f");
    // if (exists) {
    // System.out.println("exists is true");
    // } else {
    // System.out.println("exists is false");
    // }
    // }

    // redis - session
    @RequestMapping("/getUser")
    @Cacheable(value = "user-key")
    public User getUser() {
        User user = new User("aa@126.com", "aa", "aa123456", "aa", "123");
        System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
        return user;
    }

    @RequestMapping("/uid")
    String uid(HttpSession session) {
        UUID uid = (UUID) session.getAttribute("uid");
        if (uid == null) {
            uid = UUID.randomUUID();
        }

        // update session
        session.setAttribute("uid", uid);
        return session.getId();
    }
}
